package com.wy.service;

import com.wy.dao.RoomDao;
import com.wy.model.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @描述
 * @创建人 wangyue
 * @创建时间2019/12/216:28
 */
@Service
public class RoomServiceImpl implements RoomService{

    @Autowired
    private RoomDao roomDao;

    public List<Room> list() {
        return roomDao.findAll();
    }

    public List<Room> list(Room room) {
       // return roomDao.findByCodeLike("%"+room.getCode()+"%");
        return roomDao.getlist2(room.getCode());
    }
    //分页查询
    public Page<Room> pagelist(int page, int size) {
        //单纯根据页码和页码大小
       // PageRequest pageable = PageRequest.of(page, size);
        //直接根据Direction 和字段名进行排序
       // Pageable pageable=PageRequest.of(page, size, Sort.Direction.DESC,"price");

        //根据sort对象进行排序
        Sort sort = new Sort(Sort.Direction.ASC,"code");
         Pageable pageable = PageRequest.of(page,size,sort);
        return roomDao.findAll(pageable);
    }
    //条件查询
    @Override
    public Page<Room> pagelist(Room room, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        Page<Room> pagelist = roomDao.findByCodeLikeAndStateOrderByCodeDesc("%"+room.getCode()+"%",room.getState(),pageable);
        /*Page<Room> pagelist = roomDao.findAll(new Specification<Room>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<Room> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate pd = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = pd.getExpressions();
                //构建查询条件
                if(room != null){
                    if(room.getCode() != null){
                        expressions.add(criteriaBuilder.like(root.get("code"),"%"+room.getCode()+"%"));
                    }
                    if(room.getState() != null){
                        expressions.add(criteriaBuilder.equal(root.get("state"),room.getState()));
                    }
                }
                return pd;
            }
        }, pageable);*/
        return pagelist;
    }

    public Room save(Room room) {


        String id=room.getId();
        if(id == null || id.equals("")){
            room.setId(UUID.randomUUID().toString());
        }
        return roomDao.save(room);
    }

    public void delete(String id){
        roomDao.deleteById(id);
    }

    public  Room getById(String id){
        return roomDao.getOne(id);
    }
}
